package com.gbas.server.http;

import com.info3k.jdbctemplate.JDBCException;
import com.info3k.jdbctemplate.JDBCTemplate;
import org.apache.log4j.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Date;

public class MusServerListener implements ServletContextListener {
    private static Logger logger = Logger.getLogger(MusServerListener.class);

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
            String jndi = servletContextEvent.getServletContext().getInitParameter("JNDI");
            if (jndi == null) {
                jndi = "java:comp/env/jdbc/MUSDS";
            }
            JDBCTemplate.inicializaJNDIDatasource(jndi);
        } catch (Exception e) {
            logger.warn("Error inicializando JNDI ...", e);
        }


        try {
            final String queryTablaCreate = "CREATE TABLE MUS_ARRANQUES(FECHAHORA TIMESTAMP )";
            JDBCTemplate.executeUpdate(queryTablaCreate);
            final String queryInsertDate = "INSERT INTO MUS_ARRANQUES(FECHAHORA) VALUES (?)";

            Integer insert = JDBCTemplate.executeUpdate(queryInsertDate, new Object[]{new Date()});

            if (insert == 1) {
                logger.info("Fecha actual anotada como arranque");
            } else {
                logger.error("Fecha actual NO se anoto como arranque");
            }
        } catch (JDBCException e) {
            logger.error("Excepcion JDBC", e);  //To change body of catch statement use File | Settings | File Templates.
        }


    }


    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
}
